import React from 'react';
import { Tree, Spin } from 'antd';
import { connect } from 'umi';

class DeptTree extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
    };
  }
  onSelect = (selectedKeys: any, info: any) => {
    this.props.setCurrent(info.node);
  };
  onDbSelect = (selectedKeys: any, info: any) => {
    console.log(selectedKeys, info);
  };
  componentDidMount() {
    this.props.onRef(this);
    this.fetchData();
  }
  fetchData = () => {
    this.props
      .dispatch({
        type: 'Abp/getTreeList',
        payload: {},
        control: 'Department',
      })
      .then(() => {
        const dataSource = this.mapData(this.props.response.result);
        this.setState({ dataSource });
      });
  };
  onCheck = (checkedKeys: any, info: any) => {
    this.props.setParent(info.node);
  };
  mapData = (parentNode: any) => {
    const treeData: any = [];
    if (parentNode) {
      parentNode.map((item: any) => {
        const node = {
          title: item.deptName,
          key: item.id,
          item: item,
          children: item.children ? this.mapData(item.children) : null,
        };
        treeData.push(node);
      });
    }
    return treeData;
  };
  render() {
    const { dataSource } = this.state;
    return (
      <div>
        {dataSource && dataSource.length ? (
          <Tree
            checkable
            defaultExpandAll
            onSelect={this.onSelect}
            onDoubleClick={this.onDbSelect}
            onCheck={this.onCheck}
            treeData={dataSource}
          />
        ) : (
          <Spin />
        )}
      </div>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(DeptTree);
